<script setup>
import { ref, computed, watchEffect, onMounted } from "vue";
import { useRoute } from "vue-router";
import { router } from "@/router";
import { useScroll, hooksData } from "./hooks/useScroll";
const { scrollRef, scrollToBottom } = useScroll();
import { ElMessage } from "element-plus";
import { CopyDocument } from "@element-plus/icons-vue";

// Conversation and PDF preview panel toggle control
let showTab = ref("nav-tab-chat");
let tabWidth = ref("");
const isReplying = ref(false);
// 提问框文字
const prompt = ref("");
const route = useRoute();
let { uuid } = route.params;
var conversationList = ref([]);
var messageList = ref([]);
let conversations = window.localStorage.getItem("chatStore");
onMounted(() => {
    if (!uuid || uuid === "0") {
        handleAdd(); // 自动创建新对话
    }
});
function initializeMessageList() {
    messageList.value = [
        {
            role: "assistant",
            content: "你好！有什么可以帮助你的吗？",
            finish_reason: "stop",
        },
    ];
}
if (conversations) {
    conversationList.value = JSON.parse(conversations);
} else {
    conversationList.value = [];
}
// Check if new conversation
if (!uuid || uuid === "0") {
    uuid = Date.now().toString();

    // Initialize empty conversation
    if (!conversations) {
        conversationList.value.push({
            title: "新对话",
            uuid: uuid,
            isEdit: false,
            createDate: new Date().toLocaleString(),
            lastChatContent: "欢迎使用策问",
            active: true,
        });
        initializeMessageList();
    } else {
        // If has history, get last conversation
        let lastConversation =
            conversationList.value[conversationList.value.length - 1];
        uuid = lastConversation.uuid;

        let messages = window.localStorage.getItem(uuid);
        if (messages) {
            messageList.value = JSON.parse(messages);
        } else {
            initializeMessageList();
        }

        router.push({ name: "Chat", params: { uuid } });
    }
} else {
    // Load current conversation messages
    let messages = window.localStorage.getItem(uuid);
    if (messages) {
        messageList.value = JSON.parse(messages);
    } else {
        initializeMessageList();
    }

    conversationList.value.forEach((item, index) => {
        if (item.uuid == uuid) {
            item.active = true;
        } else {
            item.active = false;
        }
    });

    scrollToBottom();
}

//  新增对话框
function handleAdd() {
    if (isReplying.value) {
        cancelReply(); // 如果机器人正在回复，取消回复
    }
    // 初始化一个空的新对话
    uuid = Date.now().toString();
    initializeMessageList();
    conversationList.value.forEach((item) => (item.active = false));

    conversationList.value.unshift({
        title: "新对话",
        uuid: uuid,
        isEdit: false,
        createDate: new Date().toLocaleString(),
        lastChatContent: "欢迎使用策问",
        active: true,
    });

    window.localStorage.setItem(
        "chatStore",
        JSON.stringify(conversationList.value)
    );
    window.localStorage.setItem(uuid, JSON.stringify(messageList.value)); // 保存新对话的空消息列表
}

// 切换对话框
function handleSwitch(selectedUuid) {
    if (isReplying.value) {
        cancelReply(); // 如果机器人正在回复，取消回复
    }
    uuid = selectedUuid;
    let messages = window.localStorage.getItem(selectedUuid);
    if (messages) {
        messageList.value = JSON.parse(messages);
    }

    conversationList.value.forEach((item, index) => {
        item.active = item.uuid === selectedUuid;
    });

    router.push({ name: "Chat", params: { uuid } });
    scrollToBottom();
}

// 提交信息
function handleSubmit() {
    fullAssistantResponse = "";
    onConversation();
    resetTextareaHeight();
}
function cleanJsonString(input) {
    // 将控制字符替换为其转义序列
    return input.replace(/\n/g, "<br>");
}

// 发送消息按钮
async function onConversation() {
    let message = prompt.value;
    if (!message || message.trim() === "") return;
    prompt.value = "";
    isReplying.value = true;
    const loadingMessage = { role: "user", content: message };
    messageList.value.push(loadingMessage);
    let lastMessage = messageList.value
        .filter((msg) => msg.role === "assistant")
        .pop();
    if (lastMessage.content.length > 0) {
        lastMessage.finish_reason = "stop";
    }
    scrollToBottom();

    let data = {
        chatId: "abcd",
        stream: true,
        detail: false,
        messages: [{ content: message, role: "user" }],
    };

    try {
        let lines = hooksData();
        lines.forEach((line) => {
            let jsonString = line.substring("data: ".length);
            if (jsonString.trim() !== "[DONE]") {
                // 转义 JSON 字符串中的控制字符
                try {
                    let escapedJsonString = cleanJsonString(jsonString);
                    let jsonPart = JSON.parse(escapedJsonString);
                    if (jsonPart.choices && jsonPart.choices.length > 0) {
                        jsonPart.choices.forEach((choice) => {
                            if (choice.delta && choice.delta.content) {
                                displayMessageCharacterByCharacter(
                                    choice.delta.content,
                                    choice.finish_reason
                                );
                            }
                        });
                    }
                } catch (e) {
                    console.error("Error parsing JSON:", e);
                }
            }
        });
    } catch (e) {
        console.error("Error during fetch or processing:", e);
    } finally {
        console.log(isReplying.value, "isReplying");
        isReplying.value = false; // 结束回复时，设置为 false
    }
}
let timeoutId = ref(null); // 用于跟踪 setTimeout 的 ID
let fullAssistantResponse = ""; // 存储全部接收到的内容
let displaying = ref(false);
let messageQueue = []; // 添加一个队列来存储待显示的消息
let finishReason = [];
// 确保队列中的消息被处理
watchEffect(() => {
    // 当不再显示时，检查队列是否有内容需要显示
    if (!displaying.value && messageQueue.length > 0) {
        displayMessageCharacterByCharacter(
            messageQueue.shift(),
            finishReason.shift()
        );
    }
    scrollToBottom();
});
// 自动保存 messageList 到 localStorage
watchEffect(() => {
    if (uuid) {
        window.localStorage.setItem(uuid, JSON.stringify(messageList.value));
    }
});

function displayMessageCharacterByCharacter(content, finish_reason) {
    if (content && content.trim() !== "") {
        if (!displaying.value) {
            displaying.value = true;

            let index = 0;
            const interval = 50; // 字符显示间隔
            let lastAssistantMessage = messageList.value
                .filter((msg) => msg.role === "assistant")
                .pop();

            if (
                !lastAssistantMessage ||
                lastAssistantMessage.finish_reason === "stop"
            ) {
                lastAssistantMessage = {
                    role: "assistant",
                    content: "",
                    finish_reason: null,
                };
                messageList.value.push(lastAssistantMessage);
            }

            const addContentCharByChar = () => {
                if (index < content.length) {
                    if (
                        content.charAt(index) === "<br>" &&
                        content.charAt(index + 1) === "<br>"
                    ) {
                        lastAssistantMessage.content += "<br>"; // 使用 <br> 标签来在HTML中进行换行
                        index += 2; // 跳过两个字符
                    } else if (
                        content.charAt(index) === "<br>" &&
                        content.charAt(index + 1) !== "<br>"
                    ) {
                        lastAssistantMessage.content += ""; // 添加当前字符
                        index++; // 跳过当前字符
                    } else {
                        lastAssistantMessage.content += content.charAt(index);
                        index++;
                    }
                    timeoutId.value = setTimeout(
                        addContentCharByChar,
                        interval
                    );
                } else {
                    lastAssistantMessage.finish_reason = finish_reason;
                    displaying.value = false;
                }
            };

            addContentCharByChar();
        } else {
            // 将内容加入队列处理
            messageQueue.push(content);
            finishReason.push(finish_reason);
        }
    }
}
function cancelReply() {
    if (timeoutId.value) {
        clearTimeout(timeoutId.value); // 取消正在进行的 setTimeout
    }
    displaying.value = false;
    isReplying.value = false;
}

function resizeTextarea() {
    const textareaElement = event.target;
    textareaElement.style.height = "auto"; // 重置高度使内容能够适配
    textareaElement.style.height = `${textareaElement.scrollHeight}px`; // 设置为滚动高度以适应所有内容
}
// 删除对话框
function handleDele(selectedUuid) {
    conversationList.value = conversationList.value.filter(
        (item) => item.uuid !== selectedUuid
    );
    window.localStorage.removeItem(selectedUuid); // 删除对应的 localStorage 数据

    if (uuid === selectedUuid) {
        uuid = null;
        messageList.value = [];
    }

    window.localStorage.setItem(
        "chatStore",
        JSON.stringify(conversationList.value)
    );
}

let mouseOver = ref(false);
const textarea = ref(null);
function handleMouseEnter() {
    if (prompt.value.length === 0) {
        mouseOver.value = true;
    }
}
function handleMouseLeave() {
    mouseOver.value = false;
}
function resetTextareaHeight() {
    if (textarea.value) {
        textarea.value.style.height = "auto"; // 重置高度为auto
    }
}
function refreshData(index) {
  const topPrompt = messageList.value[index-1].content
  prompt.value = topPrompt
  messageList.value.splice(index,1)
  onConversation()
  console.log(topPrompt,messageList.value);
  // console.log(messageList.value[index-1],index);
}
function copy(params) {
    let repParams = params.replace(/<br>/g, "");

    navigator.clipboard.writeText(repParams).then(() => {
        ElMessage({
            message: "复制成功",
            type: "success",
        });
    });
}
const dianzanActive = ref(false);
const daozanActive = ref(false);
function toggleColor() {
    dianzanActive.value = !dianzanActive.value;
    if(dianzanActive.value){
      daozanActive.value = false
    }
}
function daozanColor() {
    daozanActive.value = !daozanActive.value;
    if(daozanActive.value){
      dianzanActive.value = false
    }
}
const dianzanColorSty = computed(() => {
  return dianzanActive.value ? '#007acc' : '#606266';
});
const daozanColorSty = computed(() => {
  return daozanActive.value ? '#c01759' : '#606266';
});
</script>

<template>
    <div id="layout" class="theme-cyan">
        <div
            class="sidebar border-end py-xl-4 py-3 px-xl-4 px-3"
            :style="tabWidth"
        >
            <div class="tab-content">
                <!-- Chat Records -->
                <div
                    class="tab-pane fade active show"
                    id="nav-tab-chat"
                    role="tabpanel"
                    v-if="showTab === 'nav-tab-chat'"
                >
                    <div
                        class="d-flex justify-content-between align-items-center mb-4"
                    >
                        <h3 class="mb-0 text-primary">策问</h3>
                        <div>
                            <button
                                class="btn btn-dark"
                                type="button"
                                @click="handleAdd"
                            >
                                新对话
                            </button>
                        </div>
                    </div>
                    <ul class="chat-list">
                        <li
                            class="header d-flex justify-content-between ps-3 pe-3 mb-1"
                        ></li>
                        <li
                            v-for="(item, index) in conversationList"
                            :class="[item.active ? 'active' : '']"
                            @click="handleSwitch(item.uuid)"
                            :key="index"
                        >
                            <div class="hover_action">
                                <button
                                    type="button"
                                    class="btn btn-link text-info"
                                >
                                    <i class="zmdi zmdi-eye"></i>
                                </button>
                                <button
                                    type="button"
                                    class="btn btn-link text-danger"
                                    @click="handleDele(item.uuid)"
                                >
                                    <i class="zmdi zmdi-delete"></i>
                                </button>
                            </div>
                            <a href="#" class="card">
                                <div class="card-body">
                                    <div class="media">
                                        <div class="avatar me-3">
                                            <span
                                                class="status rounded-circle"
                                            ></span>
                                            <img
                                                class="avatar rounded-circle"
                                                :style="[
                                                    item.active
                                                        ? 'filter:grayscale(0)'
                                                        : 'filter:grayscale(1)',
                                                ]"
                                                src="../assets/chatgpt.png"
                                                alt="avatar"
                                            />
                                        </div>
                                        <div class="media-body overflow-hidden">
                                            <div
                                                class="d-flex align-items-center mb-1"
                                            >
                                                <h6
                                                    class="text-truncate mb-0 me-auto"
                                                >
                                                    {{ item.title }}
                                                </h6>
                                                <p
                                                    class="small text-muted text-nowrap ms-4 mb-0"
                                                >
                                                    {{ item.createDate }}
                                                </p>
                                            </div>
                                            <div class="text-truncate">
                                                {{ item.lastChatContent }}
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </a>
                        </li>
                    </ul>
                </div>
            </div>
        </div>
        <div class="main px-xl-5 px-lg-4 px-3">
            <div class="chat-body">
                <!-- Chat Box Header -->
                <div class="chat-header border-bottom py-xl-4 py-md-3 py-2">
                    <div class="container-xxl">
                        <div class="row align-items-center">
                            <div class="col-6 col-xl-4">
                                <div class="media">
                                    <div class="me-3 show-user-detail">
                                        <span
                                            class="status rounded-circle"
                                        ></span>
                                        <img
                                            class="avatar rounded-circle"
                                            src="../assets/chatgpt.png"
                                            alt="avatar"
                                        />
                                    </div>
                                    <div class="media-body overflow-hidden">
                                        <div
                                            class="d-flex align-items-center mb-1"
                                        >
                                            <h6
                                                class="text-truncate mb-0 me-auto title-text"
                                            >
                                                策问
                                            </h6>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
                <!-- end Chat Box Header -->

                <div class="chat-content" id="scrollRef" ref="scrollRef">
                    <div class="container-xxl">
                        <ul class="list-unstyled py-4">
                            <li
                                v-for="(item, index) in messageList"
                                :key="index"
                            >
                                <!-- 用户提问 -->
                                <div
                                    v-if="item.role === 'user'"
                                    class="d-flex message right"
                                >
                                    <div class="message-body">
                                        <span
                                            class="date-time text-muted"
                                        ></span>
                                        <div
                                            class="message-row d-flex align-items-center justify-content-end"
                                        >
                                            <div
                                                class="message-content border p-3"
                                            >
                                                {{ item.content }}
                                            </div>
                                        </div>
                                    </div>
                                    <div class="mr-lg-3 me-2">
                                        <img
                                            class="avatar sm rounded-circle"
                                            src="../assets/user.png"
                                            alt="avatar"
                                        />
                                    </div>
                                </div>

                                <!-- 机器人响应回答 -->
                                <div
                                    v-else-if="item.role == 'assistant'"
                                    class="d-flex message"
                                >
                                    <div class="mr-lg-3 me-2">
                                        <img
                                            class="avatar sm rounded-circle"
                                            src="../assets/chatgpt.png"
                                            alt="avatar"
                                        />
                                    </div>
                                    <div class="message-body">
                                        <div
                                            class="message-row d-flex align-items-center"
                                        >
                                            <div class="message-content p-3">
                                                <!-- {{ item.content }} -->
                                                <div
                                                    v-html="item.content"
                                                ></div>
                                                <div
                                                    style="
                                                        height: 40px;
                                                        position: relative;
                                                    "
                                                >
                                                <i
                                                        @click="copy(item.content)"
                                                        class="fuzhi iconfont icon-fuzhi"
                                                    ></i>
                                                   <i
                                                        @click="refreshData(index)"
                                                        class="shuaXin iconfont icon-shuaxin"
                                                    ></i>
                                                   
                                                    <i
                                                        @click="toggleColor"
                                                        :style="{
                                                            color: dianzanColorSty,
                                                        }"
                                                        class="dianZan iconfont icon-dianzan"
                                                    ></i>
                                                    <i
                                                        @click="daozanColor"
                                                        :style="{
                                                            color: daozanColorSty,
                                                        }"
                                                        class="daoZan iconfont icon-daozan"
                                                    ></i>
                                                    
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </li>
                        </ul>
                    </div>
                </div>
                <div class="chat-footer border py-xl-4 py-lg-2 py-2">
                    <div class="css-1yy90g1">
                        <div class="css-p1nhsf">
                            <div class="css-hg8u7"></div>
                            <div class="css-18cbd93">
                                <textarea
                                    v-model="prompt"
                                    ref="textarea"
                                    rows="1"
                                    placeholder="输入问题"
                                    class="chakra-textarea css-1p3qni"
                                    @keydown.enter.exact.prevent="handleSubmit"
                                    @input="resizeTextarea"
                                ></textarea>
                                <div
                                    class="css-yymjw2"
                                    :class="[
                                        {
                                            'mouse-over-disabled':
                                                mouseOver &&
                                                prompt.length === 0,
                                        },
                                        {
                                            'text-btn-bgc': prompt.length > 0,
                                        },
                                    ]"
                                    @mouseenter="handleMouseEnter"
                                    @mouseleave="handleMouseLeave"
                                    @click="handleSubmit"
                                >
                                    <span tabindex="0" class="css-1baulvz">
                                        <svg
                                            xmlns="http://www.w3.org/2000/svg"
                                            viewBox="0 0 16 16"
                                            fill="none"
                                            class="chakra-icon css-ee6or9"
                                            focusable="false"
                                        >
                                            <path
                                                d="M.5 1.163A1 1 0 0 1 1.97.28l12.868 6.837a1 1 0 0 1 0 1.766L1.969 15.72A1 1 0 0 1 .5 14.836V10.33a1 1 0 0 1 .816-.983L8.5 8 1.316 6.653A1 1 0 0 1 .5 5.67V1.163Z"
                                                fill="currentColor"
                                            ></path>
                                        </svg>
                                    </span>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</template>
<style scoped>
.main {
    padding: 16px;
    background-color: #f4f4f7;
    margin-right: 0px;
}
.el-icon {
    font-size: 20px;
}
.sidebar {
    background-color: #f4f4f7;
    border-right: 1px solid #dfe2ea !important;
}
.btn.btn-dark {
    background-color: #3571ff;
    border-color: #3571ff;
    color: var(--white-color);
}
.sidebar {
    padding: 16px !important;
}
.tab-content {
    background-color: #fff;
    padding: 12px;
    border-radius: 12px;
    border: 1px solid #dfe2ea;
    height: 96vh;
}
.css-1yy90g1 {
    margin: 10px auto;
    max-width: min(800px, 100%);
    padding-inline-start: 1.25rem;
    padding-inline-end: 1.25rem;
}
.css-p1nhsf {
    padding-top: 18px;
    padding-bottom: 18px;
    position: relative;
    box-shadow: rgba(0, 0, 0, 0.2) 0px 0px 10px;
    border-radius: 8px;
    background: #fff;
    overflow: hidden;
    border: 1px solid rgba(0, 0, 0, 0.12);
}
.css-yymjw2 {
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    right: 1rem;
    bottom: 12px;
    width: 32px;
    background-color: #e5e5e5;
    height: 32px;
    border-radius: 5px;
}
.css-ee6or9 {
    display: inline-block;
    line-height: 1em;
    flex-shrink: 0;
    color: #fff;
    width: 20px;
    height: 20px;
    box-sizing: content-box;
    vertical-align: top;
    fill: currentcolor;
}
.css-1p3qni {
    width: 100%;
    font-size: 1rem;
    padding-inline-start: 1rem;
    padding-inline-end: 1rem;
    border-radius: 8px;
    outline: transparent solid 2px;
    outline-offset: 2px;
    position: relative;
    appearance: none;
    transition: background-color 200ms, border-color 200ms, color 200ms,
        fill 200ms, stroke 200ms, opacity 200ms, box-shadow 200ms,
        transform 200ms;
    padding-top: 0px;
    padding-bottom: 0px;
    vertical-align: top;
    background: inherit;
    padding-left: 1.2rem;
    padding-right: 48px;
    border: 0;
    resize: none;
    line-height: 22px;
    max-height: 50vh;
    overflow-y: auto;
    white-space: pre-wrap;
    word-break: break-all;
    color: #111824;
    box-shadow: none !important;
}
.text-btn-bgc {
    background-color: #487fff !important;
    cursor: pointer;
}
.mouse-over-disabled {
    cursor: not-allowed;
}
.chat-header .container-xxl {
    max-width: none;
}
.main .chat-body .chat-content .message .avatar {
    border: 1px solid #fff;
}
.avatar {
    height: 50px;
    width: 50px;
}
.avatar.sm {
    height: 50px;
    width: 50px;
    font-size: 12px;
}
.title-text {
    margin-top: 14px;
    font-size: 20px;
}
.text-primary {
    color: #163954 !important;
}
.chat-list li.active a {
    border-color: #3571ff;
}
.chat-list li:hover {
    border-color: #3571ff;
}
.main .chat-body {
    background-color: #fff;
    border-radius: 12px;
    margin-left: -2.5%;
    width: 105%;
}
.main .chat-body .chat-content {
    border-left: 1px solid #dfe2ea !important;
    border-right: 1px solid #dfe2ea !important;
}
.main .chat-body {
    height: 96vh;
}
.border,
.border-top,
.border-end,
.border-bottom,
.border-start {
    border-color: #dfe2ea !important;
}
.main .chat-body .chat-header {
    border-radius: 12px 12px 0 0;
    border: 1px solid #dfe2ea !important;
}
.avatar.sm {
    height: 40px;
    width: 40px;
    font-size: 12px;
}
.main .chat-body .chat-footer {
    border-radius: 0 0 12px 12px;
}
.text-primary {
    font-family: "Georgia", "Times New Roman", serif;
    font-size: 24px;
    font-weight: bold;
}
.btnCopy {
    position: absolute;
    top: 0;
    bottom: 0;
    margin: auto;
}
.dianZan {
    position: absolute;
    left: 70px;
}
.daoZan {
    position: absolute;
    left: 104px;
    font-size: 21px;
}
.shuaXin{
  position: absolute;
    left: 34px;
    font-size: 20px;
}
.fuzhi{
  position: absolute;
}
.list-unstyled li{
  margin-bottom: 10px;
}
</style>
